<?php

namespace App\Controller\Admin;

use App\Entity\ChatKeyword;
use App\Entity\ChatRule;
use App\Model\ChatRuleModel;
use App\Repository\ArticleRepository;
use App\Repository\ChatRuleRepository;
use App\Setting\ChatRuleSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\ChatRule as Entity;
use Symfony\Component\HttpFoundation\Response;

/**
 * @route("/admin/")
 */
class ChatRuleController extends BaseController4Admin
{

    /**
     * @route("ChatRule/create",name="ChatRuleCreate")
     */
    public function ChatRuleCreate(ChatRuleRepository $repository)
    {
        if(!$name = $this->getParamRequired("name")){return $this->json_out(400,"请输入规则名称");}
        if(!$keywords = $this->getParamRequired("keywords")){return $this->json_out(0,"请设置关键词");}
        if(!$reply = $this->getParamRequired("reply")){return $this->json_out(0,"请设置回复内容");}
        if(!$replyType = $this->getParamRequired("replyType")){$replyType = 0;}
        if(!$price = $this->getParamRequired("price")){$price = 0;}

//        $data["name"] = $name;
//        $data["keywords"] = $keywords;
//        $data["reply"] = $reply;
//        $data["replyType"] = $replyType;
//        $data["$price"] = $price;

        if($id = $this->getParamRequired("id")){
            if (!$rule = $repository->find($id)) {
                $rule = new ChatRule();
            }
        }else{
            $rule = new ChatRule();
        }
        $rule->setName( $name);

        //处理回复
        $rule->setReplyType($replyType)
            ->setPrice($price)
            ->setReply($reply);
        $this->myEm()->persist($rule);
        $this->myEm()->flush();
        //处理关键词
        $old = $rule->getKeywords()->getValues();
        foreach ($old as $one) {
            $rule->removeKeyword($one);
            $this->myEm()->remove($one);
            $this->myEm()->flush();
        }
        foreach ($keywords as $new) {
            $ck = new ChatKeyword();
            $ck->setFlag($new["flag"])
                ->setText($new["text"])
                ->setRule($rule);
            $this->myEm()->persist($ck);
        }

        $this->myEm()->flush();
        $this->setGroups("rule");
        $rule = $this->serialize($rule);

        return $this->json_out(200,"OK",$rule);

    }


    /**
     * @route("ChatRule/add/vue",name="vueAdd")
     */
    public function vueAdd()
    {
        return $this->render("/Admin/ChatRule/vue_edit.php.twig");
    }



    /**
     * @route("ChatRule/add",name="ChatRulePreAdd")
     */
    public function add()
    {

        return $this->redirectToRoute("vueAdd");

        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new ChatRuleSetting($this->getDoctrine()));
        $entity = "";
        if (!$entity) {$entity = new $this->entitySetting->entityPath();}
        $setting = new ChatRuleSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("ChatRuleDoAdd"));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true,
        );
        return $this->show("Admin/ChatRule/edit.php.twig",$data);
    }

    /**
     * @route("ChatRule/add/do",name="ChatRuleDoAdd")
     *
     *
     */
    public function doAdd(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $entity = new Entity();
        if (!$entity) {
            $entity = new $this->entitySetting->entityPath();
        }
        $setting = new ChatRuleSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];//传参
            return $this->js_out("保存成功",$this->generateUrl("ChatRuleLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("ChatRulePreAdd"));
        }
    }

    /**
     * @route("ChatRule/edit/{id}",name="ChatRulePreEdit")
     */
    public function edit(Entity $entity)
    {
        $url = $this->generateUrl("vueAdd")."#/?id=".$entity->getId();
        return $this->redirect($url);

        return $this->redirectToRoute("vueAdd",["id"=>$entity->getId()]);
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ChatRuleSetting($this->getDoctrine()));
        $setting = new ChatRuleSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("ChatRuleDoEdit",["id"=>$entity->getId()]));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => false,
        );
        return $this->show("Admin/ChatRule/edit.php.twig",$data);
    }

    /**
     * @route("ChatRule/edit/{id}/do",name="ChatRuleDoEdit")
     *
     *
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ChatRuleSetting($this->getDoctrine()));
        $setting = new ChatRuleSetting($this->getDoctrine());
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            /**@var $entity Entity*/
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = [];
            return $this->js_out("保存成功",$this->generateUrl("ChatRuleLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("ChatRulePreEdit",array("id"=>$entity->getId())));
        }
    }

    /**
     * @route("ChatRule",name="ChatRuleLists")
     */
    public function lists()
    {
        $uid = $this->needToBeAdmin();
        //私有部分
        $tools = array();
        //通用部分
        $this->setSetting(new ChatRuleSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new ChatRuleModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("ChatRuleTools"),
            "addUrl"=>$this->generateUrl("ChatRulePreAdd"),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        $config = $this->entitySetting->formConfig();
        $data = array(
            'title'     => "$entityCnName 列表",
            "tools"     => $tools,
            'urls'      => $urls,
            "config"    => $config,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("ChatRuleLists"),$total,$per_page),
        );
        return $this->show("Admin/ChatRule/list.php.twig",$data);
    }

    /**
     * @route("ChatRule/tools",name="ChatRuleTools")
     */
    public function tools(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new ChatRuleSetting($this->getDoctrine()));
        return $this->comTools($request);
    }

    /**
     * @route("ChatRule/copy/{id}",name="ChatRuleDoCopy")
     *
     * @Method({"GET", "POST"})
     */
    public function doCopy(Request $request,Entity $entity)
    {
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = new Entity();
        foreach ($tmp as $key => $value) {
            if ($key == "id") {continue;}
            $funcGet = "get".ucfirst($key);
            $funcSet = "set".ucfirst($key);
            $en->$funcSet($entity->$funcGet());
        }
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->redirectToRoute("ChatRuleLists");
    }


    /**
     * @\Symfony\Component\Routing\Annotation\Route("ChatRule/reply/{id}",name="ChatRuleShowReply")
     *
     */
    public function ChatRuleShowReply(Entity $entity,ArticleRepository $articleRepository)
    {
        $tmp = $entity;
        $reply = $entity->getReply();
        $str = "";
        foreach ($reply as $one) {
            if ($one["type"]=="text") {
                $str .=("<p>文本：{$one["content"]}</p>");
            }
            if ($one["type"]=="article") {
                $art = $articleRepository->find($one["content"]);
                if ($art) {
                    $str .=("<p>文章：{$art->getTitle()}</p>");
                }else{
                    $str .=("<p>文章：【原文已删除】</p>");
                }
            }
        }
        return new Response($str,200);

    }
}
